﻿using System.Collections.Generic;
using System.Linq;

namespace DynamicGeometry
{
    public class ReplaceFigureAction : GeometryAction
    {
        public ReplaceFigureAction(Drawing drawing, IFigure figure, IFigure replacement)
            : base(drawing)
        {
            Figure = figure;
            Replacement = replacement;
        }

        public IFigure Figure { get; set; }
        public IFigure Replacement { get; set; }
        public IFigure[] Dependents { get; set; }

        protected override void ExecuteCore()
        {
            Dependents = Figure.Dependents.ToArray();
            Figure.SubstituteWith(Replacement);
            RecalculateDependents();
        }

        void RecalculateDependents()
        {
            Drawing.Recalculate();
        }

        protected override void UnExecuteCore()
        {
            foreach (var dependent in Dependents)
            {
                dependent.ReplaceDependency(Replacement, Figure);
            }
            Figure.Dependents.AddRange(Dependents);
            RecalculateDependents();
        }
    }
}
